<template>
    <!-- 投诉列表 -->
    <n-card :bordered="false">
        <BasicTable :columns="columns" :request="loadDataTable" :row-key="(row) => row.id" ref="actionRef"
            :action-column="actionColumn" :scroll-x="1090" :striped="true" :show-selection="true"
            @update:checked-row-keys="onCheckedRow">
            <template #tableTitle>
                <n-button type="error" @click="batchDelete" :disabled="checkedRowKeys.length === 0" class="ml-2">
                    批量删除
                </n-button>

                <!-- 排序选择器 -->
                <div class="ml-auto flex items-center">
                    <n-icon size="20" @click="reloadTable" class="cursor-pointer hover:text-primary transition-colors">
                        <Reload />
                    </n-icon>

                    <div class="ml-5 flex items-center cursor-pointer" @click="toggleSortOrder">
                        <span class="mr-2">时间排序</span>
                        <img src="@/assets/images/report/up.png" class="w-[20px] h-[20px]"
                            v-show="sortOrder === 'desc'" />
                        <img src="@/assets/images/report/down.png" class="w-[20px] h-[20px]"
                            v-show="sortOrder === 'asc'" />
                    </div>
                </div>
            </template>
        </BasicTable>
    </n-card>

    <!-- 查看详情弹窗 -->
    <n-modal v-model:show="showDetailModal" title="投诉详情" preset="dialog" :show-icon="false" :width="800">
        <div v-if="currentComplaint" class="flex flex-col gap-5 p-2.5">
            <div class="flex flex-col gap-3">
                <p class="font-semibold text-sm m-0">投诉图片：</p>
                <div v-if="currentComplaint.images?.length" class="flex flex-wrap gap-3">
                    <n-image v-for="(imgUrl, index) in currentComplaint.images" :key="index + imgUrl" :src="imgUrl"
                        alt="投诉图片" class="w-[calc((100%-24px)/3)] max-h-[200px] object-cover rounded-md border border-gray-200
                        cursor-pointer transition-transform hover:scale-102" />
                </div>
                <div v-else class="text-center text-gray-500 p-5 bg-gray-50 rounded-md">暂无图片</div>
            </div>

            <!-- 投诉内容 -->
            <div class="flex flex-col gap-2">
                <p class="font-semibold m-0 text-sm">投诉内容：</p>
                <p class="m-0 whitespace-pre-line break-words leading-relaxed text-gray-800">
                    {{ currentComplaint.content || '暂无投诉内容' }}
                </p>
            </div>
        </div>
    </n-modal>

    <!-- 图片预览弹窗 -->
    <n-modal v-model:show="showPreviewModal" title="图片预览" preset="dialog" :show-icon="false" :width="600">
        <img :src="previewImageUrl" alt="预览图片" class="w-full max-h-[500px] object-contain rounded-md" />
    </n-modal>
</template>

<script lang="ts" setup>
import { h, ref, reactive } from 'vue';
import { BasicTable, TableAction } from '@/components/Table';
import { useMessage, useDialog, NImage, NTag, NIcon } from 'naive-ui';
import { debounce } from 'lodash-es';
import { Reload } from "@vicons/ionicons5"

// API
import { getComplaintList, deleteComplaint } from '@/api/report/index';

// --- Refs & Reactive ---
const message = useMessage();
const dialog = useDialog();

// Table
const actionRef = ref<any>(null);
const checkedRowKeys = ref<(string | number)[]>([]);

// 排序、弹窗状态
const sortOrder = ref<string>('desc'); // 默认排序：从新到旧 (up.png 对应 desc)
const showDetailModal = ref<boolean>(false);
const currentComplaint = ref<any>(null);
const showPreviewModal = ref<boolean>(false);
const previewImageUrl = ref<string>('');

// --- Table Columns Definition ---
const columns = [
    {
        title: '图片',
        key: 'images',
        align: 'center',
        width: 160,
        render(record) {
            if (!record.images || record.images.length === 0) {
                return h(NTag,
                    { type: 'warning', style: { cursor: 'default' } },
                    { default: () => '无' }
                );
            }
            const firstImage = record.images[0];
            return h(NImage, {
                src: firstImage,
                alt: '投诉图片',
                class: 'w-20 h-15 object-cover rounded-md cursor-pointer !p-0 !border-0'
            });
        },
    },
    {
        title: '投诉内容',
        key: 'content',
        align: 'center',
        minWidth: 400,
        render(record) {
            return h('div', {
                class: 'whitespace-nowrap overflow-hidden text-ellipsis w-full'
            }, record.content || '暂无投诉内容');
        }
    },
];

// --- Action Column Definition ---
const actionColumn = reactive({
    width: 220,
    title: '操作',
    key: 'action',
    align: 'center',
    fixed: 'right',
    render(record) {
        return h(TableAction as any, {
            style: 'text',
            actions: [
                {
                    label: '查看',
                    type: 'primary',
                    onClick: () => handleView(record),
                },
                {
                    label: '删除',
                    type: 'error',
                    onClick: () => handleDelete(record),
                },
            ],
        });
    },
});

// --- Methods ---
// 选中行防抖处理
const handleCheckedRowChange = debounce((keys: (string | number)[]) => {
    checkedRowKeys.value = keys;
}, 50);

const onCheckedRow = (keys: (string | number)[]) => {
    handleCheckedRowChange(keys);
};

// 加载数据（带排序参数）
const loadDataTable = async (params) => {
    const query = {
        ...params,
        sort: sortOrder.value
    };
    return await getComplaintList(query);
};

const reloadTable = () => {
    actionRef.value.reload();
};

const toggleSortOrder = () => {
    sortOrder.value = sortOrder.value === 'desc' ? 'asc' : 'desc';
    reloadTable();
};

// 打开详情弹窗
const handleView = (record) => {
    currentComplaint.value = record;
    showDetailModal.value = true;
};

// 图片预览函数
const previewImage = (imgUrl) => {
    previewImageUrl.value = imgUrl;
    showPreviewModal.value = true;
};

// 单条删除
const handleDelete = async (record) => {
    dialog.warning({
        title: '确认删除',
        content: `确定要删除这条投诉记录吗？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
            await deleteComplaint([record.id]);
            message.success('删除成功');
            reloadTable();
        },
    });
};

// 批量删除
const batchDelete = async () => {
    if (checkedRowKeys.value.length === 0) return;

    dialog.warning({
        title: '确认批量删除',
        content: `确定要删除选中的 ${checkedRowKeys.value.length} 条投诉记录吗？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
            await deleteComplaint(checkedRowKeys.value as number[]);
            message.success('批量删除成功');
            checkedRowKeys.value = [];
            reloadTable();
        },
    });
};
</script>